<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>用户登陆</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="../static/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../static/css/user_login.css" media="all">
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<div id="container">
    <div class="user-login-background">
        <div class="admin-header">
            <span>登录</span>
        </div>
        <form class="login_form">
            <div>
                <i class="layui-icon layui-icon-username admin-icon"></i>
                <input type="text" name="username" id="mobile" placeholder="请输入手机号" autocomplete="off"
                       class="layui-input admin-input admin-input-username" value="">
            </div>
            <div>
                <i class="layui-icon layui-icon-password admin-icon"></i>
                <input type="password" name="password" id="password" placeholder="请输入密码" autocomplete="off"
                       class="layui-input admin-input admin-input-verify" value="">
            </div>
            <button class="layui-btn admin-button" type="submit">登 陆</button>
            <div class="down_link">还没有账号？<a href="javascript:;" class="to_register">立即注册</a></div>
        </form>
    </div>
    <div class="user-register-background">
        <div class="admin-header">
            <span>注册</span>
        </div>
        <form class="register_form" action="">
            <div>
                <i class="layui-icon layui-icon-username admin-icon"></i>
                <input type="text" name="mobile" id="register_mobile" placeholder="请输入手机号" autocomplete="off"
                       class="layui-input admin-input admin-input-username" value="">
            </div>
            <div>
                <input type="text" name="image_captcha" id="image_code" placeholder="请输入图片验证码" autocomplete="off"
                       class="layui-input admin-input" value="">
                <img class="admin-captcha get_pic_code" width="90" height="30" src="../static/images/captcha.jpg"
                     onclick="generateImageCode()">
            </div>
            <div>
                <input type="text" name="sms_captcha" id="sms_code" placeholder="请输入短信验证码" autocomplete="off"
                       class="layui-input admin-input" value="">
                <a href="javascript:;" class="get_sms_code get_code" onclick="sendSMSCode()">点击获取验证码</a>
            </div>
            <div>
                <i class="layui-icon layui-icon-password admin-icon"></i>
                <input type="password" name="password" id="register_password" placeholder="请输入注册密码" autocomplete="off"
                       class="layui-input admin-input admin-input-verify" value="">
            </div>
            <button class="layui-btn admin-button" type="submit">注 册</button>
            <div class="down_link">已有账号？<a href="javascript:;" class="to_login">立即登陆</a></div>
        </form>
    </div>
</div>
<script src="../static/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'jquery'], function () {
        var form = layui.form,
            $ = layui.$,
            layer = layui.layer;

        $(function () {
            // 登录框和注册框切换
            $('.to_register').click(function () {
                $('.user-login-background').hide();
                $('.user-register-background').show();
                generateImageCode();
            })

            // 登录框和注册框切换
            $('.to_login').click(function () {
                $('.user-login-background').show();
                $('.user-register-background').hide();
            })

            // TODO 注册按钮点击
            $(".register_form").submit(function (e) {
                // 阻止默认提交操作,不让其往默认的action提交
                e.preventDefault()

                // 取到用户输入的内容
                var mobile = $("#register_mobile").val()
                var sms_code = $("#sms_code").val()
                var password = $("#register_password").val()

                if (!mobile) {
                    layer.msg('手机号不能为空！');
                    return;
                }
                if (!sms_code) {
                    layer.msg('手机验证码不能为空！');
                    return;
                }
                if (!password) {
                    layer.msg('密码不能为空！');
                    return;
                }

                if (password.length < 6) {
                    layer.msg('密码长度不能小于6位！');
                    return;
                }

                // 发起注册请求
                //拼接请求参数
                var params = {
                    "mobile": mobile,
                    "sms_code": sms_code,
                    "password": password
                }

                $.ajax({
                    url: '/passport/register',
                    type: 'post',
                    data: JSON.stringify(params),
                    contentType: 'application/json',
                    headers: {'X-CSRFToken': getCookie('csrf_token')},
                    success: function (resp) {
                        //判断是否注册成功
                        if (resp.errno == '0') {
                            //重新加载当前页面
                            layer.msg('注册成功!请登录！', function () {
                                window.location = './';
                            });
                        } else {
                            layer.msg(resp.errmsg);
                        }
                    }
                })
            })

            // TODO 登录表单提交
            $(".login_form").submit(function (e) {
                e.preventDefault()
                var mobile = $(".login_form #mobile").val()
                var password = $(".login_form #password").val()

                if (!mobile) {
                    layer.msg('账号不能为空！');
                    return;
                }

                if (!password) {
                    layer.msg('密码不能为空！');
                    return;
                }

                // 发起登录请求
                // 拼接参数
                var params = {
                    "mobile": mobile,
                    "password": password
                }

                $.ajax({
                    url: '/passport/login',
                    type: 'post',
                    data: JSON.stringify(params),
                    contentType: 'application/json',
                    headers: {'X-CSRFToken': getCookie('csrf_token')},
                    success: function (resp) {
                        //判断是否登陆成功
                        if (resp.errno == '0') {
                            layer.msg('登录成功', function () {
                                window.location = './user_index';
                            });
                        } else {
                            layer.msg(resp.errmsg);
                        }
                    }
                })

            })

        })
        var imageCodeId = ""
        var preimageCodeId = ""

        // TODO 生成一个图片验证码的编号，并设置页面中图片验证码img标签的src属性
        window.generateImageCode = function generateImageCode() {


            //1.生成一个随机字符串
            imageCodeId = generateUUID();

            //2.拼接图片url地址
            image_url = '/passport/image_code?cur_id=' + imageCodeId + "&pre_id=" + preimageCodeId

            //3.将地址设置到image标签的src属性中,为image_url
            $('.get_pic_code').attr('src', image_url)

            //4.记录上一次的编号
            preimageCodeId = imageCodeId
        }

        // 发送短信验证码
        window.sendSMSCode = function sendSMSCode() {
            // 校验参数，保证输入框有数据填写
            //移除按钮点击事件
            $(".get_sms_code").removeAttr("onclick");
            var mobile = $("#register_mobile").val();
            if (!mobile) {
                layer.msg('请填写正确的手机号!', function () {
                    $(".get_sms_code").attr("onclick", "sendSMSCode();");
                });
                return;
            }
            var imageCode = $("#image_code").val();
            if (!imageCode) {
                layer.msg('请填写验证码!', function () {
                    $(".get_sms_code").attr("onclick", "sendSMSCode();");
                });
                return;
            }

            // TODO 发送短信验证码
            //拼接参数
            var params = {
                "mobile": mobile,
                "image_code": imageCode,
                "image_code_id": imageCodeId
            }

            //发送获取短信请求
            $.ajax({
                url: '/passport/sms_code',//请求地址
                type: 'post',
                data: JSON.stringify(params),
                contentType: 'application/json',
                headers: {'X-CSRFToken': getCookie('csrf_token')},
                success: function (resp) {
                    //判断是否请求成功
                    if (resp.errno == '0') {

                        //定义倒计时时间
                        var num = 60;

                        //创建定时器
                        var t = setInterval(function () {

                            //判断是否倒计时结束
                            if (num == 1) {
                                //清除定时器
                                clearInterval(t)
                                //设置标签点击事件,并设置内容
                                $(".get_sms_code").attr("onclick", 'sendSMSCode()');
                                $(".get_sms_code").html('点击获取验证码');


                            } else {
                                //设置秒数
                                num -= 1;
                                $('.get_code').html(num + '秒');
                            }
                        }, 1000);//一秒走一次

                    } else {//发送失败
                        alert(resp.errmsg);
                        // 重新设置点击事件,更新图片验证码
                        $(".get_sms_code").attr("onclick", 'sendSMSCode()');
                        generateImageCode();
                    }
                }
            })
        }

        function getCookie(name) {
            var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
            return r ? r[1] : undefined;
        }

        function generateUUID() {
            var d = new Date().getTime();
            if (window.performance && typeof window.performance.now === "function") {
                d += performance.now(); //use high-precision timer if available
            }
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        }
    });
</script>
</body>
</html>